<?php

namespace App\Console\Commands;

use App\Services\Bank\BankServiceFactory;
use Illuminate\Console\Command;

class SyncBankDetailsCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'bank:sync-details
                            {--account= : 指定银行账号}
                            {--days=1 : 同步天数，1表示当日，大于1表示历史明细}
                            {--bank=BankOfHangzhou : 银行代码}
                            {--stats-only : 只显示统计信息，不执行同步}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步银行入账明细数据';

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $bank = $this->option('bank');

        // 获取银行服务
        try {
            $bankService = BankServiceFactory::make($bank);
        } catch (\Exception $e) {
            $this->error("无法创建银行服务: {$e->getMessage()}");
            return 1;
        }

        // 如果只是查看统计信息
        if ($this->option('stats-only')) {
            $this->showStats($bankService);
            return 0;
        }

        $account = $this->option('account') ?: config("bank.banks.{$bank}.test_account");
        $days = (int) $this->option('days');

        if (!$account) {
            $this->error('未指定银行账号，请使用 --account 参数或在配置文件中设置 test_account');
            return 1;
        }

        $this->info('开始同步银行明细数据...');
        $this->line("银行: {$bank}");
        $this->line("账号: {$account}");
        $this->line("天数: {$days}" . ($days === 1 ? ' (当日明细)' : ' (历史明细)'));
        $this->newLine();

        // 执行同步
        $result = $bankService->syncDetailsToDatabase($account, $days);

        // 显示结果
        if ($result['success']) {
            $this->info('✓ 银行明细同步完成');
            $this->line("同步批次: {$result['sync_batch_id']}");
            $this->line("成功同步: {$result['total_synced']} 条");
            $this->line("错误数量: {$result['total_errors']} 条");

            if (!empty($result['details'])) {
                $this->newLine();
                $this->info('详细结果:');
                foreach ($result['details'] as $key => $detail) {
                    $this->line("  {$key}:");
                    $this->line("    - 成功: {$detail['synced_count']} 条");
                    if (isset($detail['duplicate_count'])) {
                        $this->line("    - 重复: {$detail['duplicate_count']} 条");
                    }
                    if (isset($detail['error_count']) && $detail['error_count'] > 0) {
                        $this->line("    - 错误: {$detail['error_count']} 条");
                    }
                }
            }
        } else {
            $this->error('✗ 银行明细同步失败');
            $this->line("错误信息: {$result['error']}");
            $this->line("同步批次: {$result['sync_batch_id']}");
        }

        $this->newLine();
        $this->info('显示最新统计信息:');
        $this->showStats($bankService, $result['sync_batch_id']);

        return $result['success'] ? 0 : 1;
    }

    /**
     * 显示同步统计信息
     *
     * @param mixed $bankService 银行服务实例
     * @param string|null $batchId
     */
    private function showStats($bankService, string $batchId = null): void
    {
        $stats = $bankService->getSyncStats($batchId);

        if (isset($stats['error'])) {
            $this->warn($stats['error']);
            return;
        }

        $headers = ['项目', '数值'];
        $rows = [
            ['同步批次', $stats['sync_batch_id']],
            ['总记录数', $stats['total_count']],
            ['未匹配', $stats['unmatched_count']],
            ['已匹配', $stats['matched_count']],
            ['已忽略', $stats['ignored_count']],
            ['总金额', number_format($stats['total_amount'], 2) . ' 元'],
            ['同步开始时间', $stats['sync_start_time']],
            ['同步结束时间', $stats['sync_end_time']],
        ];

        $this->table($headers, $rows);
    }
}